/**
 * Created by Toma on 2016/6/12.
 * 基于Zepto.Ajax 图片上传，表单提交, 模拟微信上传图片接口。
 */

/**
 * 上传图片咯
 * @param option 默认配置
 * @constructor
 */
function ImageUpload(option) {
  this.option = option || {
        test: 'php/com.php', // 测试上传图片的地址
        url: 'php/com.php', // 提交地址
        status: $('#showstatus'), // 显示当前状态
        subtn: $('#imgup'), // 显示当前状态
        imgbeforeSend: function () {
          this.status.html('图片上传中');
          this.subtn.prop('disabled',true);
        },
        imgsuccess:function () {
          this.status.html('图片上传成功');
          this.subtn.prop('disabled',false);
        }
      };

  this.data = {}; // 保存提交的数据
  this.images = []; // 保存上传的图片
  this.lastimg = '';
  this.deal = 1;

  this.init();
}


/**
 * 用户行为 初始化操作
 */
ImageUpload.prototype.event = function () {
  var that = this;
  var task = that.imgCase();
  this.option.subtn.tap(function () {
    task(that);
  })
};


/**
 * 判断是否测试
 * @returns {*}
 */
ImageUpload.prototype.imgCase = function () {
  if (this.option.test) {
    this.testInit();
    return this.testImg;
  } else {
    return this.wxImg;
  }
};


/**
 * 微信上传
 * @param that
 */
ImageUpload.prototype.wxImg = function (that) {
  alert('微信上传啥的')
};


/**
 * 模拟微信上传 初始化时添加iframe组件
 */
ImageUpload.prototype.testInit = function () {

  var tmp = document.createElement('iframe');
  tmp.id = 'tmpIframe';
  tmp.name = 'tmpIframe';
  tmp.style.display = 'none';
  document.body.appendChild(tmp);

  var form = document.createElement('form');
  form.id = 'tmpFileForm';
  form.action = this.option.test;
  form.method = "post";
  form.target = "tmpIframe";
  form.enctype = "multipart/form-data";
  form.style.display = 'none';
  document.body.appendChild(form);

  var azFile = document.createElement("input");
  azFile.name = "azFile";
  azFile.id = "azFile";
  azFile.type = "file";
  document.getElementById("tmpFileForm").appendChild(azFile);
};

/**
 * 模拟微信上传
 * @param that
 */
ImageUpload.prototype.testImg = function (that) {
  var file = $('#azFile'),
      fet = false;
  file.trigger('click');
  file.on('change',function () {
    if(file.val() != that.lastimg){
      $("#tmpFileForm").submit();
      that.option.imgbeforeSend();
      that.lastimg = file.val();
      fet = true;
    }
  });
  $('#tmpIframe').on('load', function () {
    var data = $(window.frames['tmpIframe'].document.body).html();
    if (data && fet) {
      that.option.imgsuccess();
      that.images.push(data);
      that.deal--;
      if(that.deal <= 0){
        that.option.subtn.html('提交信息')
      }
      alert(that.images);
    }
  });
};


/**
 * 初始化默认调用方法。
 */
ImageUpload.prototype.init = function () {
  this.event();
};
